import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:mall/core/models/ad_config.dart';
import 'package:mall/core/services/auth.dart';

// import 'package:mall_ad/mall_ad.dart';
import 'package:provider/provider.dart';

class ProductAdView extends StatefulWidget {
  @override
  _ProductAdViewState createState() => _ProductAdViewState();
}

class _ProductAdViewState extends State<ProductAdView> {
  AdConfig _adConfig;

  @override
  void initState() {
    super.initState();
    _fetchConfig();
  }

  @override
  Widget build(BuildContext context) {
    return _adConfig == null || !_adConfig.enable ? Container() : Container();
    // : MallAdView(
    //     maxSeconds: _adConfig.maxSeconds,
    //     created: (controller) {
    //       controller.fetchAd("banner", "1580");
    //     },
    //     dismiss: () {
    //       // 隐藏广告
    //       setState(() {
    //         _adConfig = null;
    //       });
    //     },
    //   );
  }

  /// 获取广告配置
  void _fetchConfig() async {
    final auth = context.read<Auth>();
    try {
      final result = await auth.adConfig();
      if (!mounted) {
        return;
      }
      final adConfig = result.firstWhere((element) => element.adPositionType == "APP_PRODUCT_AD");
      setState(() {
        _adConfig = adConfig;
      });
    } on DioError catch (e) {
      debugPrint("${e.message}");
    } catch (e) {
      debugPrint('$e');
    }
  }
}
